import React, {
    useState,
    useEffect,
    useMemo,
    useCallback,
    useLayoutEffect
} from "react";
import { connect, useDispatch } from "react-redux";
import {
    lgAlert, LgSplitLine, LgDropdown, LgTopBarContainer, BackToOfficialBlock,
    IdentityBlock,
    LogoutBlock,
    MessageBlock,
    UserBlock, SystemInfo, createClassName, SystemInfoProps
} from "lancoo-web-ui";
import $ from "jquery";

import axiosMethod from "../../util/axios";
import "./index.scss";
import { message, Upload } from "antd";

const {classNames} = createClassName("lg-top-bar");

function Header(props){
    let {
        userInfo,
        sysAddrInfo,
        sysInfo,
        currentIdentity,
        basePathName = "login.html"
    } = props;

    const dispatch = useDispatch();
    const [systemInfo, setSystemInfo] = useState({});

    const backToOfficialPlatform = () => {//返回办公平台
        // if(!sysAddrInfo["260"]){
        //     message.warn("暂未部署办公平台");
        //     return;
        // }
        console.log(sysAddrInfo)
        if (!sysAddrInfo["264"]) {
            message.warn("暂未部署办公平台")
            return
        }
        window.location.href = sysAddrInfo["264"].webSvrAddr + `homepage/web/index.html?lg_tk=${sessionStorage.getItem("token")}`
        // window.location.href = sysAddrInfo["260"].webSvrAddr + `html/index/index.html?lg_tk=${sessionStorage.getItem("token")}`;
    }

    const handLogout = () => {
        dispatch({
            type: "SET_ALERTINFO",
            data: {
                title: "确定要退出登录吗？",
                visible: true,
                onOk: function(){
                    axiosMethod({
                        type: "post",
                        url: "BaseApi/Login/Logout",
                        baseUrl: sysInfo.baseUrl,
                        body: {
                            appid: "260",
                            token: sessionStorage.getItem("token"),
                            UserID: userInfo.userId,
                            DeviceType: "2"
                        },
                        callback: function(res){
                            sessionStorage.removeItem("token");
                            localStorage.removeItem("token");
                            window.location.href = sysInfo.baseUrl + `${basePathName}`;
                        }
                    });
                },
                onCancel: function(value){
                    dispatch({
                        type: "SET_ALERTINFO",
                        data: {
                            visible: false,
                            title: "",
                            smallTitle: "",
                            data: {},
                            onOk: ()=>{},
                            onCancel: ()=>{}
                        }
                    })
                }
            }
        })
        // lgAlert.show({tipType: 'closeAll'})
        // let alert = lgAlert.show({
        //     duration: 0,
        //     content: '是否退出登录？ ',
        //     isShowCloseBtn: true,
        //     tipType: 'question',
        //     tipMouldType: 'A',
        //     tipSize: 'small',
        //     description: `You should be self-esteem, do not be arrogant`,
        //     showCover: true,
        //     coverZIndex: 5000,
        //     coverOpacity: 0.25,
        //     position: {
        //         xAxis: 'center',
        //         yAxis: 'center'
        //     },
        //     onConfirm() {
        //         axiosMethod({
        //             type: "post",
        //             url: "BaseApi/Login/Logout",
        //             baseUrl: sysInfo.baseUrl,
        //             body: {
        //                 appid: "260",
        //                 token: sessionStorage.getItem("token"),
        //                 UserID: userInfo.userId,
        //                 DeviceType: "2"
        //             },
        //             callback: function(res){
        //                 sessionStorage.removeItem("token");
        //                 localStorage.removeItem("token");
        //                 lgAlert.close(alert.index);
        //                 window.location.href = sysInfo.baseUrl + `${basePathName}`;
        //             }
        //         });
        //     },
        //     onCancel(type, positionIndex) {
        //         lgAlert.close(alert.index);
        //         // lgAlert.show({tipType: 'closeAll'})
        //     },
        // });
    }

    const loadScriptOrCss = useCallback((urlArr, num, type) => {
        var that = this;
        if (!num) {
            num = urlArr.length;
        } //正则判断是否是 css;
        var reg = RegExp(/.css/);
        if (reg.test(urlArr[num - 1])) { // 动态生成 css
            var scriptOrCss = document.createElement('link');
            scriptOrCss.type = 'text/css';
            scriptOrCss.async = 'async';
            scriptOrCss.href = urlArr[num - 1];
            scriptOrCss.rel = "stylesheet";
            document.getElementsByTagName("head")[0].appendChild(scriptOrCss);
        } else {// 动态生成 js
            var scriptOrCss = document.createElement('script');
            scriptOrCss.type = 'text/javascript';
            scriptOrCss.async = 'async';
            scriptOrCss.src = urlArr[num - 1];
            document.body.appendChild(scriptOrCss);
        } 
        if (scriptOrCss.readyState) {//IE 下
            scriptOrCss.onreadystatechange = function() {
                if (scriptOrCss.readyState == 'complete' || scriptOrCss.readyState == 'loaded') {
                    scriptOrCss.onreadystatechange = null;
                    num--;
                    if (num == 0) {
                        type && window.Agassitant(); //js 和 css 加载完成,可以直接调用小助手函数;或间 num 设全局,若 num=0 时,证明动态生成的 js 和 css 已全部加载完成.
                    } else {
                        loadScriptOrCss(urlArr, num, type);
                    }
                }
            }
        } else {//其他浏览器
            scriptOrCss.onload = function() {
                num--;
                if (num == 0) {
                    type && window.Agassitant(); //js 和 css 加载完成,可以直接调用小助手函数;或间 num 设全局,若 num=0 时,证明动态生成的 js 和 css 已全部加载完成.
                } else {
                   loadScriptOrCss(urlArr, num, type);
                }
            }
        }
    }, []);
    const loadMessage = useCallback(()=>{
        if(!sysAddrInfo["210"]){
            return;
        }
        let token = sessionStorage.getItem("token");
        let assistantURL = sysAddrInfo["210"].webSvrAddr;
        sessionStorage.setItem('PsnMgrToken', token);
        sessionStorage.setItem('PsnMgrMainServerAddr', sysInfo.baseUrl); 
        sessionStorage.setItem('PsnMgrLgAssistantAddr', assistantURL);
        loadScriptOrCss([
        assistantURL + "/PsnMgr/LgAssistant/js/lancoo.cp.assistantInfoCenter.js",
        assistantURL + "/PsnMgr/LgAssistant/assets/jquery.pagination.js",
        assistantURL + "/PsnMgr/LgAssistant/js/jquery-1.7.2.min.js",
        assistantURL + "/PsnMgr/LgAssistant/css/lancoo.cp.assistantInfoCenter.css"]);
    }, [sysAddrInfo, sysInfo, loadScriptOrCss]);
    const showMessage = useCallback(()=>{
        $("#Assistant_infoCenter").click();
    }, []);
    const selfClick = useCallback(()=>{
		let token = sessionStorage.getItem('token')
        let pathName = basePathName === "login.html"? "html/personalMgr": "/UserMgr/PersonalMgr/Default.aspx";
        window.open(sysInfo.baseUrl + `${pathName}?lg_tk=${token}`, '_blank');
    }, [sysInfo, basePathName]);
    useEffect(()=>{
        loadMessage();
    }, [loadMessage]);
    return (
        <LgTopBarContainer className="operation-app-top">
            <div className="lg-top-bar-left">
                <div className="lg-top-bar-logo">
                    <div className="lg-top-bar-logo"></div>
                </div>
                <div className="lg-top-bar-system-A">
                    <div className="lg-top-bar-system-name">平台使用及运维</div>
                </div>
            </div>
            <div className={(classNames("right"))}>

                <BackToOfficialBlock handClick={backToOfficialPlatform}/>
                <LgSplitLine margin={'0 10px'}/>
                {
                    !sysAddrInfo["210"]?
                    "":
                    <span className="top-btn">
                        <i id="Assistant_infoCenter"></i>
                        <span onClick={showMessage}>消息</span>
                    </span>
                }

                <LgSplitLine margin={'0 10px'}/>
                <div className="user-container" onClick={selfClick}>
                <UserBlock userImageUrl={userInfo.photoPath} userName={userInfo.userName} />
                </div>
                {
                    currentIdentity.isPreset?
                    <IdentityBlock identityImgUrl={currentIdentity.identityImg}>
                    </IdentityBlock>:
                    <IdentityBlock identityImgUrl={currentIdentity.identityImg}>
                        <span className={(classNames("define-identity"))}>{currentIdentity.identityName}</span>
                    </IdentityBlock>
                }

                <LogoutBlock handClick={handLogout}/>

            </div>

        </LgTopBarContainer>
    )
}

const mapProps = (state) => {
    return {
        userInfo: state.userInfo,
        sysInfo: state.sysInfo,
        sysAddrInfo: state.sysAddrInfo,
        currentIdentity: state.currentIdentity,
        basePathName: state.basePathName
    }
}
export default connect(mapProps)(Header);